package com.dragon.sso.service;

import com.dragon.sso.ldap.LDAPConnector;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author bin.wei
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

  @Qualifier("customUserDetailService")
  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired private PasswordEncoder passwordEncoder;
  @Override
  public Authentication authenticate(Authentication authentication)
      throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    UserDetails details = null;
    try {
      details = userDetailsService.loadUserByUsername(name);
    } catch (Exception e) {
      throw new BadCredentialsException(e.getMessage());
    }
    // 验证用户
    if (Objects.isNull(details)) {
      throw new BadCredentialsException("用户未找到");
    }
    if (passwordEncoder.matches(password, details.getPassword())) {
      return new UsernamePasswordAuthenticationToken(name, null, details.getAuthorities());
    }
    return null;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return true;
  }
}
